// CommandLineHelper Library
// =========================
// License: Microsoft Permissive License (Ms-PL) v1.1
// Author: Rhy Mednick (http://www.rhyverse.net)
// Project Site: http://www.codeplex.com/CommandLineHelper

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace CommandLineHelper.Attributes
{
    /// When applied to a property, this attribute instructs the command line helper parsing routine to validate 
    /// that the property value passed in matches the specified regular expression.
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public sealed class ValidatePatternAttribute : Attribute, IValidation
    {
        private RegexOptions m_options = RegexOptions.None;
        private string m_regexPattern = String.Empty;
        private string m_statusMessage = String.Empty;

        /// <summary>
        /// Gets the status message that is set when the IsValid() method is called.
        /// </summary>
        public string StatusMessage
        {
            get
            {
                return m_statusMessage;
            }
        }

        /// <summary>
        /// Gets or sets the RegexOptions to use when evaluating the regular expression.
        /// </summary>
        public RegexOptions Options
        {
            get { return m_options; }
            set { m_options = value; }
        }

        /// <summary>
        /// Gets or sets the regular expression to use for validation.
        /// </summary>
        public string RegexPattern
        {
            get { return m_regexPattern; }
            set { m_regexPattern = value; }
        }

        /// <summary>
        /// Verifies that the value matches the regular expression.
        /// </summary>
        /// <param name="value">The value to validate.</param>
        /// <returns>True if the value matches the regular expression and false if it doesn't.</returns>
        public bool IsValid(object value)
        {
            bool retval = false;
            Regex regex = new Regex(m_regexPattern, m_options);
            //regular expressions are for strings, so this is an invalid test if we're not working with strings
            string strval = value as string;

            if (!string.IsNullOrEmpty(strval))
            {
                retval = regex.IsMatch(strval);
            }

            if (!retval)
            {
                m_statusMessage = String.Format("The value '{0}' does not match the regular expression '{1}'.", strval, m_regexPattern);
            }
            return retval;
        }

    }
}
